$(function() {
    getUserAddress();

})
//添加地址
function submitAdd() {
    let url = "/address/addAddress";
    // 取出登录的用户
    let loginUser = getLoginUser();
    let userId = loginUser.userId;
    let params = {
        name: $("#addressName").val(),
        phone: $("#addressPhone").val(),
        detail: $("#addressDetail").val(),
        userId: userId
    };
    httpPost(url, params, function (data) {
    })
}
//删除地址
    function deleteAddr(addressId){
        console.log(addressId);
        var res = confirm("是否删除");
        if(res==true){
            let url = "/address/deleteAddress";
            let params = {
                addressId: addressId
            };
            httpGet(url, params, function (data) {
            });
            window.location.reload();
        }
    }
    //修改地址
    function updateAddressBtn(addressId) {
        let url = "/address/updateAddress";

        console.log(url);
        let params = {
            name: $("#updateAddressName"+addressId).val(),
            phone: $("#updateAddressPhone"+addressId).val(),
            detail: $("#updateAddressDetail"+addressId).val(),
            addressId: addressId
        };
        console.log(params);
        httpPost(url, params, function (data) {
            console.log(data)
        })
    }


    //设置默认状态
//     function defaultAddr(id){
//     var res = confirm("是否设为默认");
//     if(res==true){
//         window.location.href="${pageContext.request.contextPath}/address?method=defaultAddress&a_id="+id;
//
//     }
// }


//获取用户所有地址
function getUserAddress() {
    let url = "/address/selectAddressByUserId";
    // 取出登录的用户
    let loginUser = getLoginUser();
    let userId = loginUser.userId;
    let params={
        userId:userId
    }
    httpGet(url,params,function (data) {
        renderingUserAddress(data);
        console.log(data)
    })
}

function renderingUserAddress(AddressList) {
    let templateAddressListHtml = $("#template_address").html();
    let AddressListHtml = "";
    let tempAddressListHtml;
    let count =1;
    //遍历商品列表
    $.each(AddressList,function (index,address) {
        //后台数据填充到模板
        tempAddressListHtml=templateAddressListHtml.replace(/{count}/g,count)
            .replace(/{addressId}/g,address.addressId)
            .replace(/{addressName}/g,address.name)
            .replace(/{addressPhone}/g,address.phone)
            .replace(/{addressDetail}/g,address.detail)
            .replace(/{addressState}/g,address.status);

        AddressListHtml+=tempAddressListHtml;
        count++;
    });
    $("#addressHead").after(AddressListHtml);

}
